import { ADD, UPDATE } from './constants'
const initState = {
  todos: [
    {
      id: 1,
      todoName: '吃饭',
      isDone: true,
    },
  ],
}
export default function reducer(state = initState, action) {
  let newList
  switch (action.type) {
    case ADD:
      newList = [...state.todos]
      // 创建任务对象
      const obj = {
        id: state.todos.length ? state.todos[state.todos.length - 1].id + 1 : 1,
        isDone: false,
        todoName: action.todoName,
      }
      newList.push(obj)
      return {
        ...state,
        todos: newList,
      }

    case UPDATE:
      newList = state.todos.map((item) => {
        const result =
          item.id === action.id ? (item.isDone = !item.isDone) : undefined
        // if (item.id === action.id) {
        //   item.isDone = !item.isDone
        // }
        return { ...item }
      })
      return {
        ...state,
        todos: newList,
      }
    default:
      return state
  }
}
